package com.qlylkj.lbk.base


import android.annotation.SuppressLint
import android.annotation.TargetApi
import android.content.Intent
import android.content.res.Configuration
import android.graphics.Bitmap
import android.net.Uri
import android.net.http.SslError
import android.os.Build
import android.view.View
import android.webkit.*
import android.widget.FrameLayout
import com.qlylkj.lbk.R
import kotlinx.android.synthetic.main.activity_webview.*
import kotlinx.android.synthetic.main.layout_toolbar.*


open class WebViewActivity : BaseActivity() {

    companion object {
        const val URL = "url"
        const val TITLE = "title"
    }

    private var mWebView: WebView? = null

    private var webSettings: WebSettings? = null

    private var pageTitle: String = ""

    override fun setLayoutId() = R.layout.activity_webview

    override fun onConfigurationChanged(newConfig: Configuration) {
        try {
            super.onConfigurationChanged(newConfig)
            if (resources.configuration.orientation == Configuration.ORIENTATION_LANDSCAPE) {
                mImmersionBar.fitsSystemWindows(false).init()
            } else if (resources.configuration.orientation == Configuration.ORIENTATION_PORTRAIT) {
                mImmersionBar.fitsSystemWindows(true).statusBarColor(R.color.colorPrimary).init()
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }


    override fun initView() {
        toolbar.run {
            setNavigationOnClickListener {
                mWebView?.run {
                    if (canGoBack()) {
                        goBack()
                    } else {
                        finish()
                    }
                }
            }
        }
        mWebView = WebView(this)
        mWebView?.run {
            layoutParams = FrameLayout.LayoutParams(
                FrameLayout.LayoutParams.MATCH_PARENT,
                FrameLayout.LayoutParams.MATCH_PARENT
            )
            webViewLayout.addView(this)
        }
        initWebSettings()
    }

    override fun initData() {

    }

    @SuppressLint("AddJavascriptInterface", "SetJavaScriptEnabled")
    private fun initWebSettings() {
        webSettings = mWebView?.settings
        webSettings?.run {
            allowFileAccess = true
            layoutAlgorithm = WebSettings.LayoutAlgorithm.NARROW_COLUMNS
            setSupportZoom(true)
            builtInZoomControls = true
            useWideViewPort = true
            setSupportMultipleWindows(false)
            loadWithOverviewMode = true
            setAppCacheEnabled(true)
            databaseEnabled = true
            domStorageEnabled = true
            javaScriptEnabled = true
            setGeolocationEnabled(true)
            allowContentAccess = true
            javaScriptCanOpenWindowsAutomatically = true
            allowUniversalAccessFromFileURLs = true
            allowFileAccessFromFileURLs = true
            setAppCachePath(this@WebViewActivity.getDir("appcache", 0).path)
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                //两者都可以
                mixedContentMode = mixedContentMode//设置安全的来源
            }
            cacheMode = WebSettings.LOAD_NO_CACHE//重写使用缓存的方式
        }
        mWebView?.run {
            overScrollMode = View.OVER_SCROLL_ALWAYS
            isVerticalScrollBarEnabled = false
            webChromeClient = mWebChromeClient
            webViewClient = mWebViewClient
            val url = intent.getStringExtra(URL)
            if (intent.hasExtra(TITLE)) {
                pageTitle = intent.getStringExtra(TITLE)
                toolbarTitle.text = pageTitle
            }
            loadUrl(url)
        }
    }

    private val mWebChromeClient = object: WebChromeClient(){

        override fun onReceivedTitle(view: WebView?, title: String?) {
            super.onReceivedTitle(view, title)
            view?.run {
                title?.let {
                    toolbarTitle.text = if(!url.contains(it)) it else pageTitle
                }
            }
        }

        override fun onProgressChanged(webView: WebView?, newProgress: Int) {
            super.onProgressChanged(webView, newProgress)
        }

        override fun onJsAlert(
            view: WebView?,
            url: String?,
            message: String?,
            result: JsResult?
        ): Boolean {
            return super.onJsAlert(view, url, message, result)
        }

        override fun onJsConfirm(
            view: WebView?,
            url: String?,
            message: String?,
            result: JsResult?
        ): Boolean {
            return super.onJsConfirm(view, url, message, result)
        }

        override fun onJsPrompt(
            view: WebView?,
            url: String?,
            message: String?,
            defaultValue: String?,
            result: JsPromptResult?
        ): Boolean {
            return super.onJsPrompt(view, url, message, defaultValue, result)
        }

    }

    private val mWebViewClient = object : WebViewClient(){
        override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
            super.onPageStarted(view, url, favicon)
        }

        @TargetApi(Build.VERSION_CODES.LOLLIPOP)
        override fun shouldOverrideUrlLoading(
            view: WebView?,
            request: WebResourceRequest?
        ): Boolean {
            return true
        }

        override fun onPageFinished(view: WebView?, url: String?) {
            super.onPageFinished(view, url)
        }

        override fun onReceivedSslError(
            view: WebView?,
            handler: SslErrorHandler?,
            error: SslError?
        ) {
            //忽略SSL证书错误，继续加载页面           
            handler?.proceed()
        }

    }

    private fun appLink(url: String): Boolean {
        try {
            url.apply {
                if (!startsWith("http") && !startsWith("https") && !startsWith("ftp")) {
                    Intent().run {
                        action = "android.intent.action.VIEW"
                        data = Uri.parse(url)
                        addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                        startActivity(this)
                        finish()
                        return false
                    }
                }
            }
        } catch (e: Exception) {

        }
        return true
    }

    private fun parseScheme(url: String): Boolean {
        return if (url.contains("platformapi/startApp") || url.contains("platformapi/startapp")) {
            true
        } else Build.VERSION.SDK_INT > Build.VERSION_CODES.M && url.contains("platformapi") && (url.contains(
            "startApp"
        ) || url.contains("startapp"))
    }

    override fun onBackPressed() {
        mWebView?.run {
            if (canGoBack()) {
                goBack()
            } else {
                finish()
            }
        }
    }

    override fun onResume() {
        super.onResume()
        mWebView?.run {
            resumeTimers()
            onResume()
        }
    }

    override fun onPause() {
        super.onPause()
        mWebView?.run {
            pauseTimers()
            onPause()
        }
    }

    override fun onDestroy() {
        mWebView?.run {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                webViewLayout?.removeView(this)
                removeAllViews()
                destroy()
            } else {
                removeAllViews()
                destroy()
                webViewLayout?.removeView(this)
            }
            mWebView = null
        }
        super.onDestroy()
    }


}